/**
 * arr.filter(fn(item,index,arr),thisArg) 返回新数组--内容是符合条件的
 * https://juejin.cn/post/7037399569730109471
 */

Array.prototype.myFilter = function (fn) {
  const res = [];
  if (typeof fn !== 'function') return new TypeError('parameter1 is not a function');
  for (let i = 0; i < this.length; i++) {
    fn(this[i], i, this) && res.push(this[i]);
  }
  return res;
};

/**
 * reduce实现filter
 */
Array.prototype.myFilter = function (fn) {
  return this.reduce((res, item, index, arr) => {
    fn(item, index, arr) && res.push(item);
    return res;
  }, []);
};

const arr = [1, 2, 3, 4];
console.log(
  'filter',
  arr.myFilter(i => i % 2 == 0)
);